<?php
/** 初始化项目 */
require '../../app/app.php';
/** 初始化数据库 */
use app\util\Mysql;
$database = Mysql::init();

$client_ip = getClientIP();
$timestamp = time();
$oldtimestamp = $timestamp -300;
if (isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["captcha"])) {
    $username = $_POST["username"];
    $userpasswd = $_POST["password"];
    $code = $_POST["captcha"];
    if ($code != $_SESSION["Code"]) {
        echo "<script>alert('验证码错误!');location.href='/?c=login';</script>";
    } else {
        $i= $database->count("user_login_info",["AND"=>["ip"=>$client_ip,"logintime[>]"=>$oldtimestamp]]);
        if($i>=5){
            echo "<script>alert('密码错误次数过多，请稍后再试！');location.href='/?c=login';</script>";
            exit();
        }
        $salt = $database->select("pass_key", ["[>]user_text" => ["uid" => "id"]], "salt", ["username" => $username]);
        if (count($salt[0]) == 0) {
            echo "<script>alert('用户不存在!');location.href='/?c=login';</script>";
        } else {
            $salt = $salt[0];
            $encrypted_data = getPassword($userpasswd,$salt);
            //查询用户信息
            $user = $database->get("user_text", "*", ["username" => $username]);
            if ($user['password'] == $encrypted_data) {
                $_SESSION['username'] = $username;
                $_SESSION['imgurl'] = $user['imgurl'];
                $_SESSION['sysgrade'] = $user['sysgrade'];
                //tinymeng
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['id'] = $user['id'];
                $_SESSION['gid']=$user['gid'];
                $_SESSION['userInfo'] = $user;//存储整个用户信息
                $database->insert("user_login_info",["username"=>$username,"ip"=>$client_ip,"logintime"=>$timestamp,"ok"=>"是"]);
                echo "<script>alert('登录成功!');location.href='/admin/index.php';</script>";
            } else {
                $database->insert("user_login_info",["username"=>$username,"ip"=>$client_ip,"logintime"=>$timestamp,"ok"=>"否","content"=>"密码错误"]);
                echo "<script>alert('密码错误!');location.href='/?c=login';</script>";
            }
        }
    }
}
?>